﻿using CommandProcessor.Dispatcher;
using Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using AutoMapper;
using QuanLySanXuat.Models;
using Domain.Commands;
using Core.Common;
using Core.Extensions;
using Data.Models;


namespace QuanLySanXuat.Controllers
{
    public class OrderSummaryController : Controller
    {
        private readonly ICommandBus commandBus;
        private readonly IOrderSummaryRepository orderSummaryRepository;
        private readonly IOrderRepository orderRepository;
        private readonly IOrderProcessRepository orderProcessRepository;
        private readonly IEmployeeRepository employeeRepository;
        private readonly ICostDetailRepository costDetailRepository;
        public OrderSummaryController(ICommandBus commandBus, IOrderSummaryRepository orderSummaryRepository, IOrderRepository orderRepository, IEmployeeRepository employeeRepository, IOrderProcessRepository orderProcessRepository, ICostDetailRepository costDetailRepository)
        {
            this.commandBus = commandBus;
            this.orderSummaryRepository = orderSummaryRepository;
            this.orderRepository = orderRepository;
            this.employeeRepository = employeeRepository;
            this.orderProcessRepository = orderProcessRepository;
            this.costDetailRepository = costDetailRepository;
        }
        //
        // GET: /OrderSummary/

        public ActionResult Index()
        {
            var orderSummary = orderSummaryRepository.GetAll();
            return View(orderSummary.ToPagedList(1, 10));
        }
        public ActionResult Create(int? ID)
        {
            ViewData["OrderProcess"]= orderProcessRepository.GetMany(x=>x.Status!=1);
            //ViewData["Order"] = orderRepository.GetMany(x => x.Status == 2);
            ViewData["Employee"] = employeeRepository.GetAll();
            var orderSummary = orderSummaryRepository.GetById(ID??0);
            var oderForm = Mapper.Map<OrderSummary, OrderSummaryFormModels>(orderSummary);
            return View(oderForm);
        }
        [HttpGet]
        public JsonResult GetDetail(int? ID)
        {
            var oderProcess = orderProcessRepository.GetById(ID??0);
            
            //var oderProcess = orderProcessRepository.GetMany(x=>x.OrderID==ID);
            int quantity = 0;
            double total = 0;

            quantity = oderProcess.Quantity??0;
            var costDetails = costDetailRepository.GetMany(x => x.OrderProcessID == oderProcess.ID);
            foreach (var cost in costDetails)
            {
                total += cost.TotalCost ?? 0;
            }

            var ordersumarry = new OrderSummaryFormModels()
            {
                Quantity = quantity,
                TotalCost = total,
                UnitPrice=total/quantity,
                ProductModelID = oderProcess.Order.ProductModelID,
                OrderID=oderProcess.OrderID
                //Khong the chuyen tu class sang Json ngay duoc ma phai chuyen theo kieu ModelForm
            };
            ViewBag.ProductName = oderProcess.Order.ProductModel.Name;
            return Json(ordersumarry, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Save(OrderSummaryFormModels frm)
        {
            var form = new OrderSummaryFormModels()
            {
                ID=frm.ID,
                Code=frm.Code,
                Description=frm.Description,
                EndDate=frm.EndDate,
                Evaluation1=frm.Evaluation1,
                Evaluation2=frm.Evaluation2,
                ExaminerID=frm.ExaminerID,
                Note=frm.Note,
                OrderID=frm.HOrderID,
                Quantity=frm.Quantity,
                StartDate=frm.StartDate,
                TotalCost=frm.TotalCost,
                UnitPrice=frm.UnitPrice,
                ProductModelID = frm.ProductModelID,
                OrderProcessID=frm.HOrderProcessID
            };
            var command = Mapper.Map<OrderSummaryFormModels, CreateOrUpdateOrderSummaryCommand>(form);
            IEnumerable<ValidationResult> errors = commandBus.Validate(command);
            ModelState.AddModelErrors(errors);
            var result = commandBus.Submit(command);

            //Cap nhat trang thai cho bang oderprocess de biet cai nao da thuc hien
            var oderProcess = orderProcessRepository.GetById(frm.HOrderProcessID ?? 0);
            var oderForm = Mapper.Map<OrderProcess, OrderProcessFormModels>(oderProcess);
            var oderMand = Mapper.Map<OrderProcessFormModels, CreateOrUpdateOrderProcessCommand>(oderForm);
            oderMand.Status = 1;
             commandBus.Submit(oderMand);

            return RedirectToAction("Index");
        }
        [HttpPost]
        public ActionResult RemoveItems(string[] ProID)
        {
            //Update trang thai Order ve Status=1. Trang thai chua ket thuc san xuat
            //List<CreateOrUpdateOrderCommand> lstOrder = new List<CreateOrUpdateOrderCommand>();
            //foreach (var e in ProID)
            //{
            //    var orderID = int.Parse(e);
            //    var comand = orderSummaryRepository.GetById(orderID);
            //    var oder = comand.Order;
            //    oder.Status = 1;
            //    var oderForm = Mapper.Map<Order, OrderFormModels>(oder);
            //    var oderMand = Mapper.Map<OrderFormModels, CreateOrUpdateOrderCommand>(oderForm);
            //    lstOrder.Add(oderMand);
            //}
            //commandBus.SubmitRange(lstOrder);

            List<DeleteOrderSummaryCommand> lst = new List<DeleteOrderSummaryCommand>();
            foreach (var e in ProID)
            {
                var orderID = int.Parse(e);
                var command = new DeleteOrderSummaryCommand { ID = orderID };
                lst.Add(command);
            }
            commandBus.SubmitRange(lst);
            var model = orderSummaryRepository.GetAll();
            return PartialView("_OrderSummaryList", model.ToPagedList(1, 10));
        }
        [HttpPost]
        public ActionResult Approve(string[] ProID)
        {
            List<CreateOrUpdateOrderCommand> listt = new List<CreateOrUpdateOrderCommand>();
            foreach (var e in ProID)
            {
                var odersumaryID = int.Parse(e);
                var odersumary = orderSummaryRepository.GetById(odersumaryID);
                var ordercom = orderRepository.GetById(odersumary.OrderID ?? 0);
                var command = Mapper.Map<Order, OrderFormModels>(ordercom);
                var oder = Mapper.Map<OrderFormModels, CreateOrUpdateOrderCommand>(command);
                oder.Status = 3;
                listt.Add(oder);
            }
            //Cap nhat
            commandBus.SubmitRange(listt);
            var model = orderSummaryRepository.GetMany(x => x.Order.Status == 2);
            return PartialView("_OrderSummaryList", model.ToPagedList(1, 10));
        }
        [HttpGet]
        [ValidateInput(false)]
        public ActionResult Page(int PageID)
        {
            var oder = orderSummaryRepository.GetAll().OrderBy(x => x.Code);
            return PartialView("_OrderSummaryList", oder.ToPagedList(1, PageID));
        }
        [HttpGet]
        public ActionResult Search(string Name)
        {
            IEnumerable<OrderSummary> model;
            if (String.IsNullOrEmpty(Name))
            {
                model = orderSummaryRepository.GetAll();
            }
            else
            {
                model = orderSummaryRepository.GetMany(x => (x.Code.Contains(Name)) || (x.Order.Code.Contains(Name)));

            }
            return PartialView("_OrderSummaryList", model.ToPagedList(1, 10));
        }

    }
}
